"use client";

import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/form/input/InputField';
import { Select } from '@/components/form/Select';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';

// 类型定义
interface AddressProfile {
  address: string;
  chain: string;
  riskScore: number;
  transactionCount: number;
  totalVolumeUSD: number;
  patterns: TransactionPattern[];
  labels: any[];
}

interface TransactionPattern {
  id: string;
  type: string;
  confidence: number;
  description: string;
  frequency: number;
  avgAmount: number;
}

interface BehaviorInsight {
  id: string;
  type: string;
  title: string;
  description: string;
  severity: 'low' | 'medium' | 'high' | 'critical';
  confidence: number;
}

interface MarketImpact {
  asset: string;
  liquidityImpact: {
    immediateImpact: number;
    expectedRecoveryTime: number;
  };
  predictions: Array<{
    timeframe: string;
    expectedChange: number;
    confidence: number;
  }>;
}

const AnalysisDashboard: React.FC = () => {
  const [searchAddress, setSearchAddress] = useState('');
  const [selectedChain, setSelectedChain] = useState('ethereum');
  const [addressProfile, setAddressProfile] = useState<AddressProfile | null>(null);
  const [behaviorInsights, setBehaviorInsights] = useState<BehaviorInsight[]>([]);
  const [marketImpact, setMarketImpact] = useState<MarketImpact | null>(null);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('overview');

  const chains = [
    { value: 'ethereum', label: 'Ethereum' },
    { value: 'bsc', label: 'BSC' },
    { value: 'bitcoin', label: 'Bitcoin' },
    { value: 'polygon', label: 'Polygon' },
    { value: 'solana', label: 'Solana' }
  ];

  // Analyze address
  const analyzeAddress = async () => {
    if (!searchAddress.trim()) return;

    setLoading(true);
    try {
      // Get address profile
      const profileResponse = await fetch(
        `/api/analysis/address/${searchAddress}?chain=${selectedChain}`
      );
      const profileData = await profileResponse.json();

      if (profileData.success) {
        setAddressProfile(profileData.data.profile);
      }

      // Get behavior insights
      const insightsResponse = await fetch(
        `/api/analysis/patterns/${searchAddress}?chain=${selectedChain}`
      );
      const insightsData = await insightsResponse.json();

      if (insightsData.success) {
        setBehaviorInsights(insightsData.data.behaviors);
      }

    } catch (error) {
      console.error('Analysis failed:', error);
    } finally {
      setLoading(false);
    }
  };

  // Risk score colors
  const getRiskColor = (score: number) => {
    if (score < 30) return 'bg-green-100 text-green-800';
    if (score < 60) return 'bg-yellow-100 text-yellow-800';
    if (score < 80) return 'bg-orange-100 text-orange-800';
    return 'bg-red-100 text-red-800';
  };

  // Pattern type mapping
  const getPatternTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      deposit: 'Deposit Pattern',
      withdrawal: 'Withdrawal Pattern',
      defi_interaction: 'DeFi Interaction',
      arbitrage: 'Arbitrage Pattern',
      accumulation: 'Fund Accumulation',
      distribution: 'Fund Distribution',
      anomaly: 'Anomaly Pattern'
    };
    return labels[type] || type;
  };

  // Severity colors
  const getSeverityColor = (severity: string) => {
    const colors = {
      low: 'bg-blue-100 text-blue-800',
      medium: 'bg-yellow-100 text-yellow-800',
      high: 'bg-orange-100 text-orange-800',
      critical: 'bg-red-100 text-red-800'
    };
    return colors[severity as keyof typeof colors] || 'bg-gray-100 text-gray-800';
  };

  return (
    <div className="p-6 space-y-6">
      {/* Page Title */}
      <div>
        <h1 className="text-3xl font-bold text-gray-900">Analysis Dashboard</h1>
        <p className="text-gray-600 mt-2">Deep analysis of on-chain address behavior patterns and market impact</p>
      </div>

      {/* Search Area */}
      <Card>
        <CardHeader>
          <CardTitle>Address Analysis</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex space-x-4">
            <div className="flex-1">
              <Input
                placeholder="Enter address to analyze"
                value={searchAddress}
                onChange={(e) => setSearchAddress(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && analyzeAddress()}
              />
            </div>
            <div className="w-48">
              <Select
                value={selectedChain}
                onValueChange={setSelectedChain}
                options={chains}
              />
            </div>
            <Button 
              onClick={analyzeAddress}
              disabled={loading || !searchAddress.trim()}
            >
              {loading ? 'Analyzing...' : 'Start Analysis'}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 分析结果 */}
      {addressProfile && (
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="overview">概览</TabsTrigger>
            <TabsTrigger value="patterns">行为模式</TabsTrigger>
            <TabsTrigger value="insights">智能洞察</TabsTrigger>
            <TabsTrigger value="risk">风险评估</TabsTrigger>
          </TabsList>

          {/* 概览页面 */}
          <TabsContent value="overview" className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {/* 地址信息卡片 */}
              <Card>
                <CardHeader>
                  <CardTitle>地址信息</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <p className="text-sm text-gray-600">地址</p>
                    <p className="font-mono text-sm break-all">{addressProfile.address}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-600">区块链</p>
                    <Badge variant="outline">{addressProfile.chain.toUpperCase()}</Badge>
                  </div>
                  <div>
                    <p className="text-sm text-gray-600">风险评分</p>
                    <Badge className={getRiskColor(addressProfile.riskScore)}>
                      {addressProfile.riskScore}/100
                    </Badge>
                  </div>
                </CardContent>
              </Card>

              {/* 交易统计 */}
              <Card>
                <CardHeader>
                  <CardTitle>交易统计</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <p className="text-sm text-gray-600">交易数量</p>
                    <p className="text-2xl font-bold">{addressProfile.transactionCount}</p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-600">总交易额</p>
                    <p className="text-2xl font-bold">
                      ${addressProfile.totalVolumeUSD.toLocaleString()}
                    </p>
                  </div>
                </CardContent>
              </Card>

              {/* 标签信息 */}
              <Card>
                <CardHeader>
                  <CardTitle>地址标签</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    {addressProfile.labels.length > 0 ? (
                      addressProfile.labels.map((label, index) => (
                        <Badge key={index} variant="secondary">
                          {label.label} ({label.type})
                        </Badge>
                      ))
                    ) : (
                      <p className="text-gray-500 text-sm">暂无标签</p>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* 行为模式页面 */}
          <TabsContent value="patterns" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>检测到的交易模式</CardTitle>
              </CardHeader>
              <CardContent>
                {addressProfile.patterns.length > 0 ? (
                  <div className="space-y-4">
                    {addressProfile.patterns.map((pattern) => (
                      <div key={pattern.id} className="border rounded-lg p-4">
                        <div className="flex justify-between items-start mb-2">
                          <div>
                            <h4 className="font-semibold">{getPatternTypeLabel(pattern.type)}</h4>
                            <p className="text-sm text-gray-600">{pattern.description}</p>
                          </div>
                          <Badge variant="outline">
                            置信度: {(pattern.confidence * 100).toFixed(1)}%
                          </Badge>
                        </div>
                        <div className="grid grid-cols-2 gap-4 mt-3 text-sm">
                          <div>
                            <span className="text-gray-600">频率:</span>
                            <span className="ml-2 font-medium">{pattern.frequency}次</span>
                          </div>
                          <div>
                            <span className="text-gray-600">平均金额:</span>
                            <span className="ml-2 font-medium">
                              ${pattern.avgAmount.toLocaleString()}
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-gray-500">未检测到明显的交易模式</p>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* 智能洞察页面 */}
          <TabsContent value="insights" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>行为洞察</CardTitle>
              </CardHeader>
              <CardContent>
                {behaviorInsights.length > 0 ? (
                  <div className="space-y-4">
                    {behaviorInsights.map((insight) => (
                      <div key={insight.id} className="border rounded-lg p-4">
                        <div className="flex justify-between items-start mb-2">
                          <div>
                            <h4 className="font-semibold">{insight.title}</h4>
                            <p className="text-sm text-gray-600 mt-1">{insight.description}</p>
                          </div>
                          <div className="flex space-x-2">
                            <Badge className={getSeverityColor(insight.severity)}>
                              {insight.severity}
                            </Badge>
                            <Badge variant="outline">
                              {(insight.confidence * 100).toFixed(1)}%
                            </Badge>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-gray-500">暂无智能洞察</p>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* 风险评估页面 */}
          <TabsContent value="risk" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>风险评估</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-6">
                  {/* 风险评分图表 */}
                  <div className="text-center">
                    <div className="inline-flex items-center justify-center w-32 h-32 rounded-full border-8 border-gray-200 relative">
                      <div 
                        className="absolute inset-0 rounded-full border-8 border-transparent"
                        style={{
                          borderTopColor: addressProfile.riskScore > 70 ? '#ef4444' : 
                                         addressProfile.riskScore > 40 ? '#f59e0b' : '#10b981',
                          transform: `rotate(${(addressProfile.riskScore / 100) * 360}deg)`
                        }}
                      />
                      <div className="text-center">
                        <div className="text-2xl font-bold">{addressProfile.riskScore}</div>
                        <div className="text-sm text-gray-600">风险评分</div>
                      </div>
                    </div>
                  </div>

                  {/* 风险因子 */}
                  <div>
                    <h4 className="font-semibold mb-3">风险因子分析</h4>
                    <div className="space-y-2">
                      <div className="flex justify-between">
                        <span>交易频率异常</span>
                        <Badge variant={addressProfile.transactionCount > 100 ? "destructive" : "secondary"}>
                          {addressProfile.transactionCount > 100 ? '高' : '正常'}
                        </Badge>
                      </div>
                      <div className="flex justify-between">
                        <span>大额交易占比</span>
                        <Badge variant="secondary">正常</Badge>
                      </div>
                      <div className="flex justify-between">
                        <span>地址标签风险</span>
                        <Badge variant={addressProfile.labels.some(l => l.type === 'exchange') ? "secondary" : "outline"}>
                          {addressProfile.labels.some(l => l.type === 'exchange') ? '已知实体' : '未知'}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
};

export default AnalysisDashboard; 